package com.financing.wap.web.controller.api;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.CorpDeptDTO;
import com.financing.wap.dto.CorpFaUserDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.ICorpService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.vo.CorpDeptVO;
import com.financing.wap.vo.CorpFaUserVO;
import com.financing.wap.web.controller.BaseController;

/**
 * 机构信息API
 * @author jtl
 *
 */
@Controller("apiCropController")
@RequestMapping("/api/corp")
public class CorpController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private ICorpService corpService;

	@Autowired
	private IUserService userService;
	/**
	 * 新增机构FA
	 * @param request
	 * @param response
	 * @param dto
	 * @return
	 */
	@RequestMapping("addFa")
	@ResponseBody
	public ResultMap addCorpFa(@Valid CorpFaUserDTO dto,BindingResult validationResult,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		if (validationResult.hasErrors()) {  
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("校验不通过！" );

			return result;  
		}
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();

		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}
		String uCompany = loginUser.getUserName();
		try {
			if(StringUtils.isBlank(dto.getuMobile())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("手机号不能为空！");
				return result;
			}if(StringUtils.isBlank(dto.getuName())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("用户名不能为空！");
				return result;
			}if(StringUtils.isBlank(dto.getuEmail())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("邮箱不能为空！");
				return result;
			}if(null==dto.getuDeptId()){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("所属部门不能为空！");
				return result;
			}if(StringUtils.isBlank(dto.getuPassWord())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("密码不能为空！");
				return result;
			}
			dto.setuManagerId(corpId);
			dto.setuCompany(uCompany);
			dto.setuRole(Constants.FA_RULE_DEPT);
			dto.setuType(Constants.FA_TYPE_CORP_FA);
			String securePassword = SecureUtil.MD5EncryptAndBase64(dto.getuPassWord());//
			dto.setuPassWord(securePassword);
			dto.setCreateBy(loginUser.getLoginName());
			dto.setUpdateBy(loginUser.getLoginName());
//			CorpFaUserDTO  userDTO =reNameCheck(corpId,dto.getuMobile());
			if(userService.isMobileRegistered(dto.getuMobile())){//重名认证
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RENAME_ERROE);
				result.setMessage("userName:"+dto.getuMobile()+" has been fount! it has reName erro!" );
			}else{
				String id = corpService.addCorpFaUser(dto);
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("faId", id);
			}

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 获取所有当前机构Fa的列表
	 * @param request
	 * @param response
	 * @param dto
	 * @return
	 */
	@RequestMapping("deptList")
	@ResponseBody
	public ResultMap corpDeptList(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();
		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}

		try {
			CorpDeptVO vo = new CorpDeptVO();
			vo.setCorpId(corpId);
			List<CorpDeptDTO> list = corpService.getCorpDeptList(vo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", list);

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 获取所有当前机构Fa的列表
	 * @param request
	 * @param response
	 * @param dto
	 * @return
	 */
	@RequestMapping("faList")
	@ResponseBody
	public ResultMap corpFaList(HttpServletRequest request, HttpServletResponse response,CorpFaUserVO vo){
		ResultMap result = new ResultMap();

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();
		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		vo.setuManagerId(corpId);
		vo.setuType(Constants.FA_TYPE_CORP_FA);
		try {
			Pager pager = new Pager();
			Integer count = corpService.getCorpUserFaCount(vo);
			pager.setTotalCount(count);
			pager.setPageSize(vo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			vo.setStart(pager.getStartIndex());
			List<CorpFaUserDTO> list = corpService.getCorpUserFaList(vo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", list);
			result.setAttribute("pager", pager);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 查看机构FA详情（get）
	 * @param request
	 * @param response
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/faView/{id}",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap faView(@PathVariable String id,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();

		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}

		CorpFaUserVO vo= new CorpFaUserVO();
		try {
			vo.setId(id);
			vo.setuManagerId(corpId);
			vo.setuType(Constants.FA_TYPE_CORP_FA);
			CorpFaUserDTO dto = corpService.getCorpUserFaView(vo);
			if(dto==null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
			}else{
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("dto", dto);
			}

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;

	}




	/**
	 * 新增机构部门
	 * @param request
	 * @param response
	 * @param dto
	 * @return
	 */
	@RequestMapping("addDept")
	@ResponseBody
	public ResultMap addDept(HttpServletRequest request, HttpServletResponse response,CorpDeptVO vo){
		ResultMap result = new ResultMap();
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();

		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}

		try {
			CorpDeptDTO dto = new CorpDeptDTO();
			dto.setRemark(vo.getRemark());
			dto.setCorpId(corpId);
			dto.setDeptName(vo.getDeptName());
			dto.setCreateBy(corpId.toString());
			dto.setUpdateBy(corpId.toString());
			Integer id = corpService.insertCorpDept(dto);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("deptId", id);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 查看部门信息（get）
	 * @param request
	 * @param response
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/viewDept/{id}",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap view(@PathVariable Integer id,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();

		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}

		CorpDeptVO vo = new CorpDeptVO();
		try {
			vo.setCorpId(corpId);
			vo.setId(id);
			CorpDeptDTO dto = corpService.getCorpDeptViewById(vo);
			if(dto==null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
			}else{
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("dto", dto);
			}

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;

	}

	/**
	 * 编辑机构FA（post）
	 * @param request
	 * @param response
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/editDept",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap edit(HttpServletRequest request, HttpServletResponse response,CorpDeptVO vo){
		ResultMap result = new ResultMap();
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String corpId = loginUser.getId();

		String type = loginUser.getUType();
		if(!Constants.FA_TYPE_CORP.equals(type)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，非机构账号！");
			return result;
		}
		try {
			vo.setCorpId(corpId);
			List<CorpDeptDTO> list = corpService.getCorpDeptList(vo);
			
			if(list!=null&&list.size()>0){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RENAME_ERROE);
				result.setMessage("部门名称重复！");
				return result;
			}
			CorpDeptDTO dto = new CorpDeptDTO();
			dto.setCorpId(corpId);
			dto.setUpdateBy(corpId.toString());
			dto.setRemark(vo.getRemark());
			dto.setCorpId(corpId);
			dto.setDeptName(vo.getDeptName());
			corpService.updateCorpDept(dto);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("dto", dto);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

//
//	/**
//	 * 根据邮箱进行重名校验
//	 * @param corpId
//	 * @param uLoginName
//	 * @return
//	 */
//	private CorpFaUserDTO  reNameCheck(Integer corpId,String uLoginName){
//		CorpFaUserVO vo= new CorpFaUserVO();
//		vo.setuManagerId(corpId);
//		vo.setuType(Constants.FA_TYPE_CORP_FA);
//		vo.setuLoginName(uLoginName);
//		CorpFaUserDTO userDTO = corpService.getCorpUserFaView(vo);
//
//		return userDTO;
//	}

	
}
